package com.snailct.bpp.commons.protocol;
import com.snailct.bpp.commons.utils.PropertiesUtil;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;
import java.util.Map;


/**
 * @author andy
 */
public final class HTTPUtil {
    private static final Log logger = LogFactory.getLog(HTTPUtil.class);
    private static int TIMEOUT=2000;
    static{
        if(StringUtils.isEmpty(PropertiesUtil.getPropValue("timeout"))){
            TIMEOUT=2000;
        }else{
            TIMEOUT = Integer.parseInt(PropertiesUtil.getPropValue("timeout"));
        }
    }
    public static RespResult request(String reqData,String reqUrl){
        MultiThreadedHttpConnectionManager httpConnManager = createHttpConnectionManager();
        HttpClient httpclient = createHttpClient(httpConnManager);
        PostMethod post = new PostMethod(reqUrl);
        post.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
        int statusCode=-1;
        try {
            RequestEntity requestEntity = new ByteArrayRequestEntity(reqData.getBytes("utf-8"), "text/xml; charset=utf-8");

            post.setRequestEntity(requestEntity);

            statusCode = httpclient.executeMethod(post);
            if (statusCode == HttpStatus.SC_OK) {
                return new RespResult(RespResult.ReqStatus.OK,processResp(new BufferedInputStream(post.getResponseBodyAsStream())));
            }
        } catch (Exception e) {
            logger.error("Http request error!",e);

        }finally {
            post.releaseConnection();
        }
        return new RespResult(RespResult.ReqStatus.FAILURE,"操作失败!");
    }
    private static String processResp(InputStream responseBodyAsStream) {
        String repDataXML = null;
        try{
            if (responseBodyAsStream != null) {
                BufferedReader in = new BufferedReader(new InputStreamReader(responseBodyAsStream, "UTF-8"));
                StringBuffer sb = new StringBuffer();
                String line = "";
                String NL = System.getProperty("line.separator");
                while ((line = in.readLine()) != null) {
                    sb.append(line + NL);
                }
                in.close();
                repDataXML = sb.toString();
                //repDataXML=EncriptUtil.unzipAndUnbase64(sb.toString());
                if (repDataXML.trim().length() > 0) {
                    return repDataXML;
                }
            }
        }catch (IOException e){
            logger.error("Process response stream error!",e);
        }

        return null;
    }
    public static RespResult request(Map<String,String> reqDatas, String reqUrl){
        MultiThreadedHttpConnectionManager httpConnManager = createHttpConnectionManager();
        HttpClient httpclient = createHttpClient(httpConnManager);
        PostMethod post = new PostMethod(reqUrl);
        post.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
        int statusCode=-1;
        try {

            NameValuePair[] valuePairs = new NameValuePair[reqDatas.size()];
            int i=0;
            NameValuePair valuePair = null;
            for(String key:reqDatas.keySet()){
                valuePair = new NameValuePair(key,reqDatas.get(key));
                valuePairs[i]=valuePair;
                i++;
            }
            post.setRequestBody(valuePairs);
            statusCode = httpclient.executeMethod(post);
            if (statusCode == HttpStatus.SC_OK) {
                return new RespResult(RespResult.ReqStatus.OK,processResp(new BufferedInputStream(post.getResponseBodyAsStream())));
            }
        } catch (Exception e) {
            e.printStackTrace();

        }finally {

            if (post != null) {
                post.releaseConnection();
            }


        }
        return new RespResult(RespResult.ReqStatus.FAILURE,"操作失败!");
    }
    private static MultiThreadedHttpConnectionManager createHttpConnectionManager() {
        MultiThreadedHttpConnectionManager httpConnManager = new MultiThreadedHttpConnectionManager();
        HttpConnectionManagerParams connParams = httpConnManager.getParams();
        connParams.setConnectionTimeout(TIMEOUT);
        connParams.setSoTimeout(TIMEOUT);
        return httpConnManager;
    }

    private static HttpClient createHttpClient(HttpConnectionManager httpConnManager) {
        HttpClient httpclient = new HttpClient(httpConnManager);
        HttpClientParams params = httpclient.getParams();
        params.setParameter(HttpClientParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
        params.setParameter(HttpClientParams.WARN_EXTRA_INPUT, Boolean.TRUE);
        params.setParameter("http.connection.stalecheck", Boolean.FALSE);
        params.setParameter("http.protocol.expect-continue", Boolean.TRUE);
        params.setConnectionManagerTimeout(TIMEOUT);
        params.setSoTimeout(TIMEOUT);
        return httpclient;
    }

}
